// Copyright 2009 Google Inc. All Rights Reserved.

/**
* @fileoverview Logic for the AreYouIn gadget.
*
* @author davidbyttow@google.com (David Byttow)
*/

var ANSWER_Yes = 'y';
var ANSWER_No = 'n';
var ANSWER_Maybe = 'm';
var HOST = "http://wave-api.appspot.com/public/gadgets/areyouin";

var DEFAULT_ICONS = {};
DEFAULT_ICONS[ANSWER_Yes] = HOST + '/yes.png';
DEFAULT_ICONS[ANSWER_No] = HOST + '/no.png';
DEFAULT_ICONS[ANSWER_Maybe] = HOST + '/maybe.png';

var DEFAULT_STATUS = {};
DEFAULT_STATUS[ANSWER_Yes] = 'Yes';
DEFAULT_STATUS[ANSWER_No] = 'No';
DEFAULT_STATUS[ANSWER_Maybe] = 'Maybe';

var statusVisible = false;
var addballotitemVisible = false;
var participantsReceived = false;
var stateReceived = false;


function makeUserKey(id, key) {
    return id + ':' + key;
}

function saveValue(key, value) {
    var state = {};
    state[key] = value;
    wave.getState().submitDelta(state);
}

function onAnswer(answer) {
    var id = wave.getViewer().getId();
    saveValue(makeUserKey(id, 'answer'), answer);
}

function fixUpFields(p, answer) {
    // HACK(davidbyttow): If there is no icon present, use one.
    var icon = p.getThumbnailUrl();
    if (!icon) {
        icon = DEFAULT_ICONS[answer];
    }
    p.icon = icon;
    
    // HACK(davidbyttow): If the name is actually an id, strip the domain.
    // Currently this happens when the full profile is not yet loaded.
    var name = p.getDisplayName();
    var parts = name.split('@');
    if (parts && parts.length > 1) {
        p.displayName_ = parts[0];
    }
}

function renderPart(templateName, elementName, data) {
    var template = opensocial.template.getTemplate(templateName);
    template.renderInto(document.getElementById(elementName), data);
}

function getStatus(p) {
    return wave.getState().get(makeUserKey(p.getId(), 'status'));
}

function allowStatusChange() {
    statusVisible = true;
    $('#status-link').show();
    $("#status-link").click(function() {
        $(this).hide();
        $('#status-div').show();
        gadgets.window.adjustHeight();
        var msg = getStatus(wave.getViewer());
        $('#status-box').val(msg);
        $('#status-box').focus();
        return false;
    });

    $('#status-form').submit(function() {
        $('#status-div').hide();
        $('#status-box').blur();
        $('#status-link').show();
        setStatusMessage($("#status-box").val());
        render();
        return false;
    });
}

function allowAddBallotItem() {
    addballotitemVisible = true;
    $('#addballotitem-link').show();
    $("#addballotitem-link").click(function() {
        $(this).hide();
        $('#addballotitem-div').show();
        gadgets.window.adjustHeight();
        var msg = getStatus(wave.getViewer());
        $('#addballotitem-box').val(msg);
        $('#addballotitem-box').focus();
        return false;
    });
    
    $('#addballotitem-form').submit(function() {
        $('#addballotitem-div').hide();
        $('#addballotitem-box').blur();
        $('#addballotitem-link').show();
        addBallotItem($("#addballotitem-box").val());
        render();
        return false;
    });
}

function render() {
    var data = {};
    
    if (!stateReceived || !participantsReceived) {
        return;
    }
    
    data[ANSWER_Yes] = [];
    data[ANSWER_No] = [];
    data[ANSWER_Maybe] = [];
    data.total = 0;
    data.responded = false;
    
    if (wave.getState()) {
        keys = wave.getState().getKeys()
        ballotitems = []
        skey = "keys:"
        for (k in keys){
            key = keys[k]
            skey = skey + "\n" + key + ":" + wave.getState().get(key)
            if(key.match(/^ballotitem/) != null) {
                data['ballotitems'].push(key)
            }
        }
        
        var participants = wave.getParticipants();
        for (var i in participants) {
            var p = participants[i];
            var answer = wave.getState().get(makeUserKey(p.getId(), 'answer'));
            if (!answer) {
                continue;
            }
            
            if (p == wave.getViewer()) {
                data.responded = true;
                if (!statusVisible) {
                    allowStatusChange();
                }
                if (!addballotitemVisible) {
                    allowAddBallotItem();
                }
            }
            
            var msg = getStatus(p);
            if (answer) {
                data[answer].push(p);
                ++data.total;
                fixUpFields(p, answer);
                p.status = msg;
            }
        }
    }
    
    renderPart('ballotitems-template', 'ballotitems-table', data);
    renderPart('answers-template', 'answers-table', data);
    gadgets.window.adjustHeight();
}

function setStatusMessage(message) {
    var id = wave.getViewer().getId();
    saveValue(makeUserKey(id, 'status'), message);
}

function addBallotItem(ballotitem) {
    saveValue(makeUserKey('ballotitem', ballotitem), ballotitem);
}

function onStateChanged() {
    stateReceived = true;
    render();
}

function onParticipantChanged() {
    participantsReceived = true;
    render();
}

function main() {
    if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(onStateChanged);
        wave.setParticipantCallback(onParticipantChanged);
    }
    $('#status-link').hide();
    $('#status-div').hide();
    $('#status-box').blur();
    
    $('#addballotitem-link').hide();
    // $('#addballotitem-div').hide();
    // $('#addballotitem-box').blur();
}

gadgets.util.registerOnLoadHandler(main);

